import { lazy, Suspense, useEffect, useMemo } from 'react';
import { createBrowserRouter, RouterProvider, Navigate, useLocation, type RouteObject, matchPath, Outlet } from 'react-router-dom';
import { Spin, Result } from 'antd';
import { useAuthStore, type MenuItemType } from '../store/authStore';
import MainLayout from '../components/layout/MainLayout';
import Login from '../pages/login';

// 懒加载组件
const lazyLoadComponent = (componentPath: string) => {
    if (!componentPath || typeof componentPath !== 'string' || componentPath.trim() === '' || componentPath === 'null') {
        console.error('无效的组件路径，返回404页面', componentPath);
        return <NotFound />;
    }
    const importPath = `../${componentPath}/index.tsx`;
    // console.log('动态导入组件路径:', importPath);
    const LazyComponent = lazy(() => import(importPath)
        .catch(err => {
            console.error('组件加载失败:', err, '路径:', importPath);
            return import('../pages/dashboard');
        })
    );
    return (
        <Suspense fallback={<Spin size="large" style={{ display: 'block', margin: '50px auto' }} />}>
            <LazyComponent />
        </Suspense>
    );
};

// 404和403页面
const NotFound = () => (
    <Result status="404" title="404" subTitle="抱歉，您访问的页面不存在" />
);
const Forbidden = () => (
    <Result status="403" title="403" subTitle="抱歉，您没有访问该页面的权限" />
);

// 递归处理菜单，生成路由配置
const generateRoutes = (menus: MenuItemType[]): RouteObject[] => {
    const routes: RouteObject[] = [];
    const processMenu = (menu: MenuItemType, parentPath = ''): RouteObject => {
        // 处理后端返回的pages/前缀路径
        const cleanPath = menu.path.replace(/^pages\//, '');
        const fullPath = parentPath ? `${parentPath}/${cleanPath}` : cleanPath;
        console.log('cleanPath:', cleanPath)
        console.log('fullPath:', fullPath)
        const route: RouteObject = {
            path: cleanPath,
            element: <MainLayout />,
            children: []
        };
        if (!route.children) route.children = [];

        // 当前菜单对应的页面组件（作为默认子路由）
        if (menu.component && typeof menu.component === 'string' && menu.component.trim()) {
            const componentPath = menu.component.replace(/^pages\//, 'pages/');
            // 当前菜单对应的页面组件（作为默认子路由）
            route.children.push({
                index: true,
                element: (
                    <Suspense fallback={<Spin size="large" style={{ margin: '50px auto' }} />}>
                        {lazyLoadComponent(componentPath)}
                    </Suspense>
                )
            });
        } else {
            console.warn(`跳过无效菜单：路径=${fullPath}，组件路径无效（${menu.component}）`);
            // 可选：如果是必须显示的菜单，可替换为404组件
            // route.children.push({ index: true, element: <NotFound /> });
        }

        // 处理子菜单（递归时同样过滤无效组件）
        if (menu.children && menu.children.length > 0) {
            menu.children.forEach(child => {
                // 【关键修复】子菜单也需要校验 component
                if (child.component && typeof child.component === 'string' && child.component.trim()) {
                    const childRoute = processMenu(child, fullPath);
                    route.children?.push({
                        path: childRoute?.path,
                        element: childRoute.children?.[0]?.element || null
                    });
                } else {
                    console.warn(`跳过无效子菜单：父路径=${fullPath}，子路径=${child.path}，组件路径无效`);
                }
            });
        }

        return route;
    };

    menus.forEach(menu => routes.push(processMenu(menu)));
    return routes;
};

// 路由守卫组件（逻辑不变）
const AuthGuard = ({ children }: { children: React.ReactNode }) => {
    const { token, authMenus, isLoading } = useAuthStore();
    const location = useLocation();
    console.log('路由守卫拿到的authMenus:', authMenus)
    if (isLoading) {
        return <Spin size="large" style={{ position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }} />;
    }

    // 未登录重定向到登录页
    if (!token) {
        return <Navigate to={`/login?redirect=${location.pathname}`} replace />;
    }

    // 权限检查逻辑
    const isPathAllowed = (path: string, menus: MenuItemType[]): boolean => {
        // 提取纯路径（去除查询参数）
        const purePath = path.split('?')[0];
        for (const menu of menus) {
            const cleanMenuPath = menu.path.replace(/^pages\//, '');
            // 支持动态参数（如 /school/detail/:id 或 /school/detail?id=1）
            const menuPathRegex = new RegExp(`^${cleanMenuPath.replace(/:\w+/g, '[^/]+')}$`);
            if (menuPathRegex.test(purePath)) {
                return true;
            }
            if (menu.children && isPathAllowed(purePath, menu.children)) return true;
        }
        console.log(`路径${path}未找到匹配的菜单权限`);
        return false;
    };

    // 无权限重定向到403
    if (!isPathAllowed(location.pathname, authMenus)) {
        return <Navigate to="/403" replace />;
    }

    return <>{children}</>;
};

// 新增：封装路由匹配日志逻辑（放在Router内部）
const RouteLogger = () => {
    const location = useLocation();
    const { authMenus } = useAuthStore();
    console.log('RouteLogger路由匹配日志:', authMenus)
    const allRoutes = useMemo(() => [
        { path: '/login', element: <Login /> },
        { path: '/404', element: <NotFound /> },
        { path: '/403', element: <Forbidden /> },
        ...generateRoutes(authMenus),
        { path: '/', element: <AuthGuard><Navigate to="/dashboard" replace /></AuthGuard> },
        { path: '*', element: <Navigate to="/404" replace /> },
    ], [authMenus]);

    useEffect(() => {
        const matchedRoute = allRoutes.find(route =>
            matchPath({ path: route.path, end: true }, location.pathname)
        );
        console.log('当前URL匹配的路由:', {
            url: location.pathname,
            matchedPath: matchedRoute?.path,
            matchedElement: matchedRoute?.element?.type?.name
        });
    }, [location.pathname, allRoutes]);

    return null;
};

// 路由配置（核心变更处）
const AppRouter = () => {
    const { authMenus } = useAuthStore();
    const generatedRoutes = generateRoutes(authMenus);
    console.log('最终生成的路由:', generatedRoutes);
    // 路由配置：将所有权限路由包裹在AuthGuard中
    const router = useMemo(() => createBrowserRouter([
        // 公开路由（无需登录即可访问）
        { path: '/login', element: <Login /> },
        { path: '/404', element: <NotFound /> },
        { path: '/403', element: <Forbidden /> },

        // 权限路由统一由AuthGuard保护
        {
            path: '/',
            element: <>
                <AuthGuard><Outlet /></AuthGuard>
                <RouteLogger /> {/* 在Router内部使用useLocation */}
            </>, // 所有子路由都会经过AuthGuard校验
            children: [
                // 动态生成的权限路由（作为AuthGuard的子路由）
                ...generatedRoutes,
                // 根路径默认重定向到dashboard
                { index: true, element: <Navigate to="/dashboard" replace /> }
            ]
        },

        // 404路由（匹配所有未定义路径）
        { path: '*', element: <Navigate to="/404" replace /> },
    ]), [generatedRoutes]);

    // // 调试用：打印当前匹配的路由
    // const location = useLocation();
    // useEffect(() => {
    //     const allRoutes = router.routes;
    //     const matchedRoute = allRoutes.find(route =>
    //         matchPath({ path: route.path || '', end: true }, location.pathname)
    //     );
    //     console.log('当前匹配路由:', {
    //         url: location.pathname,
    //         matchedPath: matchedRoute?.path
    //     });
    // }, [location.pathname, router.routes]);

    return <RouterProvider router={router} />;
};

export default AppRouter;